/*
 * Created by Weiting on 2011/11/10
 * copyright 2011 III. All rights reserved.
 *
 */
package com.eslserver.action.coordinator;

import java.io.IOException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.core.ESLServerPageDispatcher;
import com.eslserver.core.aware.CoordinatorAware;
import com.eslserver.dao.DAOException;
import com.eslserver.dao.CoordinatorDAO;
import com.eslserver.dao.ESLServerDAOFactory;
import com.eslserver.to.Coordinator;

@SuppressWarnings("serial")
public class AddCoordinator extends HttpServlet implements CoordinatorAware,
		ESLServerPageDispatcher {

	public static final Logger LOG = LoggerFactory
			.getLogger(AddCoordinator.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			Integer coordinatorID = Integer.valueOf(req
					.getParameter(PARAM_COORDINATOR_ID));

			CoordinatorDAO coorDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY)
					.getCoordinatorDAO();

			Coordinator coor = null;
			Date now = new Date();
			if (coordinatorID.equals(0)) {
				coor = Coordinator.createESLCoordinator();
				coor.setCreateDate(now);
				coor.setModifyDate(now);
				coor.setDelete(false);
			} else {
				coor = coorDAO.loadCoordinatorByID(coordinatorID);
			}

			if (req.getParameter(PARAM_COORDINATOR_NAME) != null
					&& req.getParameter(PARAM_COORDINATOR_NAME).length() > 0) {
				coor.setName(req.getParameter(PARAM_COORDINATOR_NAME));
			}
			if (req.getParameter(PARAM_COORDINATOR_IP) != null
					&& req.getParameter(PARAM_COORDINATOR_IP).length() > 0) {
				coor.setIpAddress(req.getParameter(PARAM_COORDINATOR_IP));
			}
			if (req.getParameter(PARAM_COORDINATOR_PORT) != null
					&& req.getParameter(PARAM_COORDINATOR_PORT).length() > 0) {
				coor.setPort(Integer.parseInt(req
						.getParameter(PARAM_COORDINATOR_PORT)));
			}
			if (req.getParameter(PARAM_COORDINATOR_DESCRIPTION) != null) {
				coor.setDescription(req
						.getParameter(PARAM_COORDINATOR_DESCRIPTION));
			}

			if (coordinatorID.equals(0)) {
				coorDAO.addCoordinator(coor);
				coordinatorID = coor.getCoordinatorID();
			} else {
				coorDAO.updateCoordinator(coor);
			}

			req.setAttribute(ATTRIBUTE_TAB_ID, COORDINATOR_TAB_ID);
			RequestDispatcher dispatcher = req
					.getRequestDispatcher(MAIN_DASHBOARD);
			dispatcher.forward(req, resp);

		} catch (DAOException e) {
			LOG.error("Error adding Coordinator.", e);
		}
	}

}
